package org.nowcoder.leetcode.backTracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Title  : 216. Combination Sum III
 * Source : https://leetcode.cn/problems/combination-sum-iii/description/
 * Author : XrazYang
 * Date   : 2024-1-25
 */

public class LeetCode_216 {
    private List<List<Integer>> result = new ArrayList<>();
    private LinkedList<Integer> path = new LinkedList<>();

    private void backTracking3(int k, int n, int index, int sum) {
        if (sum > n) return;
        if (path.size() == k) {
            if (sum == n) {
                result.add(new ArrayList<>(path));
            }
            return;
        }
        for (int i = index; i <= 9 - (k - path.size()) + 1; i++) {
            path.add(i);
            sum += i;
            backTracking3(k, n, i + 1, sum);
            path.removeLast();
            sum -= i;
        }
    }

    public List<List<Integer>> combinationSum3(int k, int n) {
        backTracking3(k, n, 1, 0);
        return result;
    }
}
